package com.chenfan.process.event.callback;

import com.chenfan.ccp.util.start.ApplicationContextUtil;
import com.chenfan.ccp.util.tool.JsonUtil;
import com.chenfan.process.biz.ApprovalInternalBiz;
import com.chenfan.process.dto.ApprovalCallBack;
import com.chenfan.process.entity.po.ApprovalPo;
import com.chenfan.process.entity.po.ApprovalTemplatePo;
import com.chenfan.process.entity.po.ProcessNotifyPo;
import com.chenfan.process.enums.ProcessNotifyTypeEnums;
import com.chenfan.process.service.ApprovalService;
import com.chenfan.process.service.ApprovalTemplateService;
import com.chenfan.process.service.ProcessNotifyService;
import com.chenfan.process.vo.ApprovalNodeVO;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Objects;

/**
 * @author K
 * @date 2021/1/27
 */
@Deprecated
@RefreshScope
@Component
public class CallbackListener {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ApprovalService approvalService;
    @Autowired
    private ProcessNotifyService processNotifyService;
    @Autowired
    private ApprovalInternalBiz approvalInternalBiz;
    @Autowired
    private ThirdCallback thirdCallback;
    @Autowired
    private ApprovalTemplateService approvalTemplateService;

    @SneakyThrows
    @Async("threadPoolTaskExecutor")
    @EventListener({CallbackEvent.class})
    public void onApplicationEvent(CallbackEvent callbackEvent) {
        ApprovalCallBack approvalCallBack = callbackEvent.getApprovalCallBack();
        /*if (approvalCallBack.isStart()) {
            // 业务那边暂时不好处理, 在回调进行延迟发送
            int time = 2000;
            logger.info("延时时间:{} ms", time);
            Thread.sleep(time);
        }*/
        logger.info("开始回调审批:{}", JsonUtil.obj2String(callbackEvent));
        String token = callbackEvent.getToken();
        ApprovalPo approval = approvalService.findApprovalByApprovalId(approvalCallBack.getApprovalId());
        if (Objects.isNull(approval)) {
            logger.warn("找不到对应的审批单:{}", approvalCallBack.getApprovalId());
            return;
        }
        ApprovalNodeVO approvalNode = approvalInternalBiz.getApprovalNode(approval.getApprovalId());
        ApprovalTemplatePo approvalTemplate = approvalTemplateService.getById(approval.getApprovalTemplateId());
        approvalCallBack.setParam(approval.getParam());
        approvalCallBack.setServiceName(approval.getServiceName());
        approvalCallBack.setNodeName(approvalNode.getNodeName());
        approvalCallBack.setNextNodeName(approvalNode.getNextNodeName());
        Integer notifyType = ProcessNotifyTypeEnums.URL.getIndex();
        switch (ProcessNotifyTypeEnums.resolve(notifyType)) {
            case DING_DING:
            case MQ:
                break;
            case URL:
                thirdCallback.getResponseByUrl(approvalCallBack.getServiceName(), "callback", approvalCallBack, token);
                String property =
                    ApplicationContextUtil.getContext().getEnvironment().getProperty("feign.debug.enable");
                boolean debug =
                    !StringUtils.isEmpty(approvalCallBack.getNextApprovalUserId()) && StringUtils.isEmpty(property);
                // 可以产生.并且没有结束才存, 结束时已经是消息, 消息后续不统计检查
                if (debug && approvalTemplate.needNotify() && !approval.isFinish()) {
                    String[] split = approvalCallBack.getNextApprovalUserId().split(",");
                    String[] names = approvalCallBack.getNextApprovalUserName().split(",");
                    for (int i = 0; i < split.length; i++) {
                        processNotifyService.save(ProcessNotifyPo.ofDefault(approvalCallBack.getApprovalId(), approval.getApprovalTemplateId(),
                            Long.valueOf(split[i]), names[i]));
                    }
                }
                break;
            default:
        }
    }
}
